// pages/couponBag/couponBag.js
import deliveryApi from '../../service/deliveryApi'
import couponApi from '../../service/couponApi'
import { reLogin } from '../../service/request'
const app = getApp()
let codeConfig = { ...app.globalData.codeConfig }
Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		hadAuthFlag: !!wx.getStorageSync('hadAuthFlag'), // 是否授权登录
		couponType: true,
		picBaseUrl: app.globalData.picBaseUrl,
		// tabs
		currentGoods: '0',
		goodsTabs: [{
			key: '0',
			title: '未提货',
		},
		{
			key: '1',
			title: '已提货',
		}
		],
		couponGoodsList: [], // 未提货商品券list
		couponGoodsDeliveredList: [], // 已提货list
		loadTips: '上拉加载',
		upAbled: true, // 是否能上拉加载
		page: {
			startPage: 1,
			pageSize: 15,
		},
		loginFlag: false, // 是否登录
		loading: false, // loading
		defaultShow: false, // 缺省页
		// 物流
		showPupFlag: false, // 物流弹窗
		logisticsData: {},
		logisticsPic: '',
		logisticsName: '',
		// 赠送弹窗
		sendPopUpFlag: false,
		giftId: '',
		tipMsg: '', // 提货成功提示
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function (options) {
		this.setData({
			hadAuthFlag: !!wx.getStorageSync('hadAuthFlag')
		})
		if (options.tipMsg) {
			this.setData({
				tipMsg: '提货申请提交成功，请耐心等待发货！'
			})
		}
		if (app.globalData.buyGoodsToCouponBag || options.tipMsg) {
			console.log('onload 已提货')
			this.onChangeDeliveredTabs()
		} else {
			console.log('onload 未提货')
			this.onChangeNoDeliveryTabs()
		}
		if (!this.data.hadAuthFlag) {
			this.setData({
				loginFlag: true
			})
		}
		// this.checkStatus()
	},

	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow: function () {
		if (this.data.tipMsg !== '') {
			wx.showToast({
				title: this.data.tipMsg,
				icon: 'none'
			})
			this.setData({
				tipMsg: ''
			})
		}
		
		let sendGiftOverBackData = app.globalData.sendGiftOverBackData
		if (sendGiftOverBackData) {
			this.onChangeNoDeliveryTabs()
			wx.showToast({
				title: sendGiftOverBackData
			})
			app.globalData.sendGiftOverBackData = ''
		}
	},

	// 授权回调
	bindGetUserInfo(e) {
		let that = this
		console.log(e.detail.userInfo)
		wx.showLoading({
			title: '数据加载中',
		})
		if (!!e.detail.userInfo) { // 同意授权-并登陆
			wx.setStorageSync('hadAuthFlag', true)
			app.globalData.userInfo = e.detail.userInfo
			app.globalData.hadAuthUserInfo = true
			app.globalData.refreshIndexFlag = true
			reLogin().then(() => {
				wx.hideLoading()
				that.setData({
					hadAuthFlag: true
				})
				wx.reLaunch({
					url: '../couponBag/couponBag'
				})
				console.log(app.globalData.userInfo)
			})
		} else { // 不同意授权
			wx.hideLoading()
			wx.setStorageSync('hadAuthFlag', false)
			that.setData({
				hadAuthFlag: false
			})
		}
	},

	// 未提货
	onChangeNoDeliveryTabs() {
		this.setData({
			couponType: true,
			upAbled: true, // 是否能上拉加载
			'page.startPage': 1
		})
		this.getCouponGoods()
	},
	// 已提货
	onChangeDeliveredTabs() {
		this.setData({
			couponType: false,
			upAbled: true, // 是否能上拉加载
			'page.startPage': 1
		})
		this.getCouponGoodsDelivered()
	},

	// 获取未提货商品券
	getCouponGoods() {
		let that = this
		if (!that.data.hadAuthFlag) return false
		if (that.data.page.startPage === 1) {
			that.setData({
				loading: true,
				defaultShow: false,
				couponGoodsList: []
			})
		}
		couponApi.couponGoods({ ...that.data.page }).then(res => {
			wx.stopPullDownRefresh()
			if (res.data.errCode === codeConfig.errCode.SUCCESS_CODE) {
				let _goodsList = res.data.data.goodsList
				let _couponGoodsList = that.data.couponGoodsList.concat(_goodsList)
				that.setData({
					loading: false,
					couponGoodsList: _couponGoodsList
				})
				if (that.data.couponGoodsList.length === 0) {
					that.setData({
						defaultShow: true,
						upAbled: false
					})
				} else {
					that.setData({
						defaultShow: false
					})
				}
				if (_goodsList.length < that.data.page.pageSize) {
					that.setData({
						loadTips: '暂无更多数据',
						upAbled: false
					})
				} else {
					that.setData({
						loadTips: '上拉加载'
					})
				}
			} else {
				that.setData({
					loading: false
				})
				wx.showToast({
					title: res.data.msg,
					icon: 'none'
				})
			}
		}).catch(res => {
			console.log(res);
		})
	},

	// 获取已提货商品券
	getCouponGoodsDelivered() {
		let that = this
		if (!that.data.hadAuthFlag) return false
		if (that.data.page.startPage === 1) {
			that.setData({
				loading: true,
				defaultShow: false,
				couponGoodsDeliveredList: []
			})
		}

		couponApi.couponGoodsDelivered({ ...that.data.page }).then(res => {
			wx.stopPullDownRefresh()
			if (res.data.errCode === codeConfig.errCode.SUCCESS_CODE) {
				res.data.data.deliveryList.map(item => {
					switch (item.deliveryState) {
						case '0':
							item.deliveryStateDescribe = '提货中'
							break
						case '1':
							item.deliveryStateDescribe = '等待发货'
							break
						case '2':
							item.deliveryStateDescribe = '已发货'
							break
						case '3':
							item.deliveryStateDescribe = '提货完成'
							break
					}
				})
				let list = that.data.couponGoodsDeliveredList.concat(res.data.data.deliveryList)
				that.setData({
					loading: false,
					couponGoodsDeliveredList: list
				})
				if (that.data.couponGoodsDeliveredList.length === 0) {
					that.setData({
						defaultShow: true,
						upAbled: false
					})
				} else {
					that.setData({
						defaultShow: false
					})
				}
				if (res.data.data.deliveryList.length < that.data.page.pageSize) {
					that.setData({
						loadTips: '暂无更多数据',
						upAbled: false
					})
				} else {
					that.setData({
						loadTips: '上拉加载'
					})
				}
			} else {
				that.setData({
					loading: false
				})
				wx.showToast({
					title: res.data.msg,
					icon: 'none'
				})
			}
		}).catch(res => {
			console.log(res);
		})
	},

	// 点击商品券进入商品详情页
	toGoodsDetail(e) {
		let goodsId = e.currentTarget.dataset.goodsid
		wx.navigateTo({
			url: `../goodsDetail/goodsDetail?goodsId=${goodsId}`
		})
	},

	// 提货 
	onPickUpGoods(e) {
		var url = '../pickUpGoods/pickUpGoods'
		var goods = e.currentTarget.dataset.goods
		wx.navigateTo({
			url: `${url}?goodsId=${goods.couponId}&goodsName=${goods.name}&goodsCount=${goods.count}`
		})
	},
	
	// 赠送
	onSend(e) {
		let item = e.currentTarget.dataset.item
		let params = {
			couponId: item.couponId,
			couponType: '5'
		}
		wx.showLoading({
      title: '加载中'
    })
		couponApi.getCouponBalance(params).then(res => {
			wx.hideLoading()
			if (res.data.errCode === codeConfig.errCode.SUCCESS_CODE) {
				if (res.data.data.balance === '0') {
					wx.showToast({
						title: '系统正在处理您的请求，请稍候',
						icon: 'none'
					})
				} else {
					item.count = res.data.data.balance
					app.globalData.sendGiftData = item
					this.setData({
						sendPopUpFlag: true
					})
				}
			}
		})
	},

	// 关闭赠送弹窗
	onCloseSendPopUp() {
		this.setData({
			sendPopUpFlag: false
		})
	},

	// 赠送给微信好友
	onSendFriend() {
		this.onCloseSendPopUp()
		wx.navigateTo({
			url: `../sendGiftToFriend/sendGiftToFriend?sendGiftType=2`
		})
	},

	// 赠送给BU地址
	onSendBlockChainAddress() {
		wx.navigateTo({
			url: `../sendGiftToBUAddress/sendGiftToBUAddress?sendGiftType=2`
		})
		this.onCloseSendPopUp()
	},

	// 提醒发货
	onTipDeliverGoods() {
		wx.showToast({
			title: '已提醒发货，请耐心等待。',
			icon: 'none'
		})
	},

	// 物流弹窗
	showLogistics(e) {
		this.setData({
			logisticsName: e.target.dataset.item.name,
			logisticsPic: e.target.dataset.item.picUrl
		})
		var params = {
			deliveryId: e.target.dataset.item.deliveryId
		}
		deliveryApi.expressDelivery(params).then(res => {
			if (res.data.errCode === codeConfig.errCode.SUCCESS_CODE) {
				var _logisticsData = res.data.data
				_logisticsData.expressInfoList.push({ content: _logisticsData.supplierName, time: '' })
				this.setData({
					showPupFlag: true,
					logisticsData: _logisticsData
				})
			} else {
				wx.showToast({
					title: res.data.msg,
					icon: 'none'
				})
			}
		})
	},
	closePup() {
		this.setData({
			showPupFlag: false
		})
	},
	// 复制订单号
	onCopy(e) {
		var orderId = e.currentTarget.dataset.orderid
		wx.setClipboardData({
			data: orderId
		})
	},

	// 缺省页去购买按钮
	goHomePage(e) {
		wx.switchTab({
			url: '../index/index'
		})
	},

	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady: function () {

	},

	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide: function () {
		app.globalData.buyGoodsToCouponBag = false
	},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload: function () {
		app.globalData.buyGoodsToCouponBag = false
	},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
		if (this.data.hadAuthFlag) {
			this.setData({
				'page.startPage': 1,
				upAbled: true // 是否可上拉加载
			})
			if (this.data.couponType) {
				this.onChangeNoDeliveryTabs()
			} else {
				this.onChangeDeliveredTabs()
			}
		}
	},
	
	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom: function () {
		if (this.data.upAbled) {
			this.setData({
				'page.startPage': this.data.page.startPage + 1,
				loadTips: '加载中...',
			})
			if (this.data.couponType) {
				this.getCouponGoods()
			} else {
				this.getCouponGoodsDelivered()
			}
		}
	}
})